import 'dart:async';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:in_app_purchase_storekit/in_app_purchase_storekit.dart';
import 'package:in_app_purchase_storekit/store_kit_wrappers.dart';

class LYPayResult {
  final bool success;
  final String? msg;
  LYPayResult({this.success = false, this.msg});
}

class LYInAppPurchaseManager {
  LYInAppPurchaseManager._internal();
  static final LYInAppPurchaseManager _instance =
      LYInAppPurchaseManager._internal();
  static LYInAppPurchaseManager get share {
    return _instance;
  }

  final InAppPurchase _inAppPurchase = InAppPurchase.instance;
  late StreamSubscription<List<PurchaseDetails>> _subscription;
  List<ProductDetails> _products = <ProductDetails>[];
  List<PurchaseDetails> _purchases = <PurchaseDetails>[];
  bool _isAvailable = false;
  void init() async {
    final Stream<List<PurchaseDetails>> purchaseUpdated =
        _inAppPurchase.purchaseStream;
    _subscription =
        purchaseUpdated.listen((List<PurchaseDetails> purchaseDetailsList) {
      _listenToPurchaseUpdated(purchaseDetailsList);
    }, onDone: () {
      _subscription.cancel();
    }, onError: (Object error) {});
    final bool isAvailable = await _inAppPurchase.isAvailable();
    _isAvailable = isAvailable;
    if (Platform.isIOS) {
      final InAppPurchaseStoreKitPlatformAddition iosPlatformAddition =
          _inAppPurchase
              .getPlatformAddition<InAppPurchaseStoreKitPlatformAddition>();
      await iosPlatformAddition.setDelegate(LYPaymentQueueDelegate());
    }
  }

  Future<LYPayResult> applePay(Set<String> productIds) async {
    final ProductDetailsResponse productDetailResponse =
        await _inAppPurchase.queryProductDetails(productIds);
    debugPrint('========$productDetailResponse');

    /// 查询不到说明没注册
    if (productDetailResponse.error != null) {
      return LYPayResult(success: false, msg: '');
    }

    /// 查询不到商品详情说明没注册
    if (productDetailResponse.productDetails.isEmpty) {
      return LYPayResult(success: false, msg: '');
    }
    _products = productDetailResponse.productDetails;

    /// 查询成功
    ProductDetails productDetails = _products.first;
    // final _storage = FlutterSecureStorage();
    // _storage.write(key: "key", value: "value");
    late PurchaseParam purchaseParam;
    purchaseParam = PurchaseParam(
        productDetails: productDetails,

        /// 添加自己服务器上生成的订单
        applicationUserName: '');

    /// 向苹果服务器发起支付请求
    final res =
        await _inAppPurchase.buyConsumable(purchaseParam: purchaseParam);
    return LYPayResult(success: res);
  }

  Future<void> _listenToPurchaseUpdated(
      List<PurchaseDetails> purchaseDetailsList) async {
    for (final PurchaseDetails purchaseDetails in purchaseDetailsList) {
      if (purchaseDetails.status == PurchaseStatus.pending) {
        // showPendingUI();
      } else {
        if (purchaseDetails.status == PurchaseStatus.error) {
          // handleError(purchaseDetails.error!);
        } else if (purchaseDetails.status == PurchaseStatus.purchased ||
            purchaseDetails.status == PurchaseStatus.restored) {
          // final bool valid = await _verifyPurchase(purchaseDetails);
          // if (valid) {
          //   unawaited(deliverProduct(purchaseDetails));
          // } else {
          //   _handleInvalidPurchase(purchaseDetails);
          //   return;
          // }
        }
        if (purchaseDetails.pendingCompletePurchase) {
          await _inAppPurchase.completePurchase(purchaseDetails);
        }
      }
    }
  }

  void dispose() {
    if (Platform.isIOS) {
      final InAppPurchaseStoreKitPlatformAddition iosPlatformAddition =
          _inAppPurchase
              .getPlatformAddition<InAppPurchaseStoreKitPlatformAddition>();
      iosPlatformAddition.setDelegate(null);
    }
    _subscription.cancel();
  }
}

class LYPaymentQueueDelegate implements SKPaymentQueueDelegateWrapper {
  @override
  bool shouldContinueTransaction(
      SKPaymentTransactionWrapper transaction, SKStorefrontWrapper storefront) {
    return true;
  }

  @override
  bool shouldShowPriceConsent() {
    return false;
  }
}
